package cn.openea.perpartner.meily.web.controller;

import cn.openea.perpartner.common.core.exception.ServiceException;
import cn.openea.perpartner.common.core.utils.StringUtils;
import cn.openea.perpartner.common.core.utils.poi.ExcelUtil;
import cn.openea.perpartner.common.core.web.controller.BaseController;
import cn.openea.perpartner.common.core.web.domain.AjaxResult;
import cn.openea.perpartner.common.core.web.page.TableDataInfo;
import cn.openea.perpartner.meily.web.entity.RevenueRecordsArc;
import cn.openea.perpartner.meily.web.entity.dto.RevenueRecordsDTOFactory;
import cn.openea.perpartner.meily.web.entity.vo.RevenueRecordsSearchVo;
import cn.openea.perpartner.meily.web.service.IRevenueRecordsArcService;
import cn.openea.perpartner.meily.web.service.IRevenueRecordsInsService;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ysk
 * @version 1.0.1
 * @Description
 * @createTime 2023年03月22日 16:17:00
 */
@Api(tags = "收益记录管理")
@RestController
@RequestMapping("/revenueRecords")
public class RevenueRecordsController extends BaseController {

    @Resource
    private IRevenueRecordsInsService revenueRecordsInsService;
    @Resource
    private IRevenueRecordsArcService revenueRecordsArcService;
    @Resource
    private RevenueRecordsDTOFactory revenueRecordsDTOFactory;


    @ApiOperation("收益记录列表查询")
    @GetMapping("/list")
    public AjaxResult list(RevenueRecordsSearchVo searchVo) {
        startPage();
        // 先判断时间
        LocalDate endOfMonth = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
        TableDataInfo tableDataInfo = null;
        if (searchVo.getTimePeriod().isAfter(endOfMonth)) {
            // 查询时间段在当前月之后
            throw new ServiceException("查询时间错误");
        }
        BigDecimal totalAccumulatedIncome;
        if (!searchVo.isSearchHistory()) {
            tableDataInfo = getDataTable(revenueRecordsInsService.listBySearchVo(searchVo));
            totalAccumulatedIncome = revenueRecordsInsService.countCumulative(searchVo.getTimePeriod());
        } else {
            tableDataInfo = getDataTable(revenueRecordsArcService.listBySearchVo(searchVo));
            totalAccumulatedIncome = revenueRecordsArcService.countCumulative(searchVo.getTimePeriod());
        }
        if (totalAccumulatedIncome == null) {
            totalAccumulatedIncome = BigDecimal.ZERO;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", tableDataInfo.getRows());
        jsonObject.put("total", tableDataInfo.getTotal());
        jsonObject.put("totalAccumulatedIncome", totalAccumulatedIncome);
        return AjaxResult.success(jsonObject);
    }

    @ApiOperation("收益记录导出")
    @PostMapping("/export/list")
    public void export(@RequestBody RevenueRecordsSearchVo searchVo, HttpServletResponse response) {
        // 先判断时间
        LocalDate endOfMonth = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
        if (searchVo.getTimePeriod().isAfter(endOfMonth)) {
            // 查询时间段在当前月之后
            throw new ServiceException("查询时间错误");
        }
        List<RevenueRecordsDTOFactory.RevenueRecordsDTO> recordsDTOS = null;
        if (!searchVo.isSearchHistory()) {
            recordsDTOS = revenueRecordsInsService.listBySearchVo(searchVo)
                    .stream()
                    .map(item -> revenueRecordsDTOFactory.revenueRecordsInsToDto.apply(item))
                    .collect(Collectors.toList());
        } else {
            recordsDTOS = revenueRecordsArcService.listBySearchVo(searchVo)
                    .stream()
                    .map(item -> revenueRecordsDTOFactory.revenueRecordsArcToDto.apply(item))
                    .collect(Collectors.toList());
        }
        // 导出
        ExcelUtil<RevenueRecordsDTOFactory.RevenueRecordsDTO> util = new ExcelUtil<>(RevenueRecordsDTOFactory.RevenueRecordsDTO.class);
        util.exportExcel(response, recordsDTOS, "收益记录列表.xlsx");
    }

    /**
     * 收益发放
     *
     * @param （收益记录ids）
     * @return
     */
    @ApiOperation("收益发放")
    @PostMapping("/incomeDistribution")
    public AjaxResult incomeDistribution(@RequestBody RevenueRecordsSearchVo vo) {
        List<String> ids;
        if (vo.byIds()) {
            // 根据id
            ids = vo.getIds();
        } else {
            // 处理符合条件的全部
            ids = revenueRecordsArcService.listBySearchVo(vo)
                    .stream()
                    .filter(item -> "未结算".equals(item.getStatus()))
                    .map(RevenueRecordsArc::getId)
                    .collect(Collectors.toList());
        }
        if (ids == null) {
            return AjaxResult.error("获取不到参数！");
        }
        if (ids.size() == 1) {
            String errMsg = revenueRecordsArcService.singleBilling(ids.get(0));
            if (StringUtils.isNotBlank(errMsg)) {
                return AjaxResult.error(errMsg);
            }
            return AjaxResult.success();
        }
        revenueRecordsArcService.incomeDistribution(ids);
        return AjaxResult.success();
    }

}
